package org.glut.saltedfish.utils;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.io.InputStream;

public class MyBatisUti {
    private static final Logger logger = LoggerFactory.getLogger(MyBatisUti.class);
    private static volatile SqlSessionFactory sqlSessionFactory;

    private MyBatisUti() {} // 私有构造方法，防止实例化

    public static SqlSessionFactory getSqlSessionFactory() {
        if (sqlSessionFactory == null) {
            synchronized (MyBatisUti.class) {
                if (sqlSessionFactory == null) {
                    try {
                        String resource = "mybatis-config.xml";
                        InputStream inputStream = Resources.getResourceAsStream(resource);
                        sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
                        logger.info("MyBatis SqlSessionFactory initialized successfully.");
                    } catch (IOException e) {
                        logger.error("Failed to initialize MyBatis", e);
                        throw new RuntimeException("Error initializing MyBatis", e);
                    }
                }
            }
        }
        return sqlSessionFactory;
    }

    // 不需要手动关闭 SqlSessionFactory，通常由应用服务器管理生命周期
}